#include "Thread.hpp"
#include <sys/types.h>
#include "LockGuard.hpp"

using namespace TheardMoudle;

int tickets = 10000;
pthread_cond_t cond;
// pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void route(ThreadData *td)
{
    int i = 0;
    while (1)
    {
        LockGuard lock(td->_mutex);
        while (i)
        {
            pthread_cond_wait(&cond, td->_mutex);
            i = 0;
        }
        if (tickets > 0)
        {
            i = 1;
            td->n++;
            usleep(10);
            std::cout << "I am " << td->_name << ", git a ticket: " << tickets << std::endl;
            tickets--;
            pthread_cond_signal(&cond);
        }
        else
        {
            pthread_cond_signal(&cond);
            break;
        }
    }
}

static int threadnum = 10;

int main()
{
    std::vector<Thread> threads;
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, nullptr);

    pthread_cond_init(&cond, nullptr);
    for (int i = 1; i <= threadnum; i++)
    {
        std::string name = "thread-" + std::to_string(i);
        ThreadData *td = new ThreadData(name, &mutex);
        threads.emplace_back(name, route, td);
    }

    for (auto &t : threads)
    {
        t.Start();
    }

    for (auto &t : threads)
    {
        t.Join();
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}